package com.lemon.smartsafety.ui.activity.safe.data.contract;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.event.contract.KeepEditEvent;
import com.lemon.smartsafety.entity.event.contract.KeepRefreshEvent;
import com.lemon.smartsafety.entity.event.contract.KeepUnitEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.entity.safe.contract.KeepContractVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.KeepContactServices;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.safe.data.KeepContractAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by Cooliean on 16/3/31.
 * 维保合同
 */
public class KeepContractListActivity extends SwipeBackActivity {

    private LoggerHelper loggerHelper = new LoggerHelper(KeepContractListActivity.class);


    @Bind(R.id.tv_company_name)
    TextView                  tvCompanyName;
    @Bind(R.id.tv_contact_name)
    TextView                  tvContactName;
    @Bind(R.id.tv_contact_vali)
    TextView                  tvContactVali;
    @Bind(R.id.ripple)
    LinearLayout                ripple;
    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.ll_recent)
    LinearLayout              llRecent;
    @Bind(R.id.float_button)
    FloatingActionButton      floatButton;


    private CompanyInfo mCompanyInfo;
    private String mKeyWord = null;
    private KeepContractVo currentContract;


    private List<KeepContractVo> mDataList = new ArrayList<>();
    private KeepContractAdapter mAdapter;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyInfo = (CompanyInfo) getIntent().getSerializableExtra(BundleKey.COMPANY_INFO);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_keep_contract_list;
    }


    @Override
    protected void initViews() {
        super.initViews();
        if (null == mCompanyInfo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
        }


        floatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProp(null);
            }
        });

        ripple.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProp(currentContract);
            }
        });

        tvCompanyName.setText(StringUtils.nullValue(mCompanyInfo.getCompany_name()));

        mAdapter = new KeepContractAdapter(mDataList);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                mPullToRefreshRecyclerView.onRefreshComplete();
                getNetData();
            }
        });
        initCurrentContractView();
        getNetData();
    }


    private void showProp(KeepContractVo vo) {
        Bundle bundle = new Bundle();
        bundle.putString(BundleKey.TYPE_ID, "1");
        bundle.putSerializable(BundleKey.COMPANY_INFO, mCompanyInfo);
        if (null != vo) {
            bundle.putSerializable(BundleKey.KEEP_CONTRACT_VO, vo);
        }
        UIHelper.showActivity(this, bundle, KeepContractPropActivity.class);
    }

    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<List<KeepContractVo>> event) {
        if (EventTag.TAG_SAFE_KEEP_CONTRACT.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    List<KeepContractVo> temp = event.getObj();
                    if (null != temp && temp.size() != 0) {
                        llRecent.setVisibility(View.VISIBLE);
                        mDataList.clear();
                        if (getCurrentContract(temp) != null) {
                            temp.remove(currentContract);
                            initCurrentContractView();
                        }
                        mDataList.addAll(temp);
                        if (mAdapter != null) {
                            mAdapter.notifyDataSetChanged();
                        }
                    } else {
                        llRecent.setVisibility(View.GONE);
                    }
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    @Subscribe
    public void onEventMainThread(KeepUnitEvent event) {
        getNetData();
    }

    @Subscribe
    public void onEventMainThread(KeepEditEvent event) {
        if (null != event.getData()) {
            showProp(event.getData());
        }
    }

    @Subscribe
    public void onEventMainThread(KeepRefreshEvent event) {
        getNetData();
    }


    private void initCurrentContractView() {
        if (currentContract != null) {
            String isGuoQi = "<font color=#35b4eb>有效</font>";
            if (currentContract.getIsDelay().equals("1")) {
                isGuoQi = "<font color=red>无效</font>";
            }
            String contractTitle = "<font color=#000000>" + currentContract.getAgencyInfoVo().getAgencyName() + "</font>";

            String vilaString = "<font color=#959595>" + currentContract.getKeep_year() + "年度，当前合同</font>" + isGuoQi;
            tvContactName.setText(Html.fromHtml(contractTitle));
            tvContactVali.setText(Html.fromHtml(vilaString));
        } else {
            tvContactName.setText(Html.fromHtml("<font color=#959595>--</font>"));
            tvContactVali.setText(Html.fromHtml("<font color=#959595>--</font>"));
        }
    }

    public KeepContractVo getCurrentContract(List<KeepContractVo> items) {
        currentContract = null;
        for (int i = 0; i < items.size(); i++) {
            KeepContractVo vo = items.get(i);
            if (StringUtils.getBoolean(vo.getStatus())) {
                currentContract = vo;
            }
        }
        return currentContract;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);
        getMenuInflater().inflate(R.menu.menu_refresh, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_refresh) {
            getNetData();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initTitle() {
        setBarTitle(R.string.safe_data_keep_contact_record);
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(KeepContractListActivity.this);
    }

    private void getNetData() {
        KeepContactServices.init().getKeepContractList(mCompanyInfo.getCompany_code(), mKeyWord, "1");
    }


}
